<?php
class Exts_Db_Table_AuditableTable extends Exts_Db_Table_Abstract {
	
	protected $_rowClass = 'Exts_Db_Table_Row_AuditableRow';
	protected $_rowsetClass = 'Exts_Db_Table_Rowset_AuditableRowset';
	protected $_currentUser = NULL;
	
	/*
	 * Pensado para pk simple; En caso de pk compuesta hay que pisar estos metodos.
	 * */
	public function findById($id){
		$primary = $this->getPk();
		return $this->fetchRow($this->select()->where("$primary = ?", $id));
	}
	
	public function fetchByUser($user){
		return $this->fetchAll($this->select()->where(" create_user = ? ", $user->user_id));
	}
	
	public function getPk () {
		if (is_array($this->_primary)) return $this->_primary[1];
		return $this->_primary;
	}
	
	
	public function setCurrentUser($user){
		$this->_currentUser = $user;
	}
	
	public function getCurrentUser(){
		return $this->_currentUser;
	}
	
	public function gotUser() {
		return $this->getCurrentUser() != NULL;
	}
	
	protected function _check() {
		if (!$this->gotUser()) {
			throw new Exts_Exception(" AuditableTable requiere tener un usuario asociado para funcionar. ");
		}
	}
	public function save ($bind) {
		$row = false;
		
		if (empty($bind)) {
			throw new Exts_Exception ("Se intentó salvar un registro vació!");
		}
		if (is_object($bind)) {
			$row = $bind;
		} else {
			
			 
			if (array_key_exists($this->getPk(), $bind) && !empty($bind [$this->getPk()])){
				
				$row = $this->findById($bind [$this->getPk()]);
			}
			
			if (!$row) {
				$row = $this->createRow();  
			}
			
			
			$row->setFromArray($bind);
			
		}

		$row->audit($this->getCurrentUser()->user_id);
		$row->save();
		return $row;
	}
	
	
	
}
